//
//  RTMP.m
//  VedioEncoder
//
//  Created by mac on 2017/6/22.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "PushStream.h"
#define RTMP_HEAD_SIZE (sizeof(RTMPPacket)+RTMP_MAX_HEADER_SIZE)
@interface PushStream ()
{
    RTMP *rtmp;
    double start_time;
    dispatch_queue_t pushQueue;
}
@end

@implementation PushStream

+(PushStream *)defaultStream
{
    static PushStream *stream;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        stream = [[self alloc]init];
    });
    return stream;
}

- (instancetype)init
{
    self = [super init];
    if(self)
    {
        rtmp = RTMP_Alloc();
        RTMP_Init(rtmp);
        RTMP_SetupURL(rtmp, "rtmp://192.168.1.137:1935/live/live");
        RTMP_EnableWrite(rtmp);
        RTMP_Connect(rtmp, nil);
        RTMP_ConnectStream(rtmp, 0);
        start_time = [[NSDate date] timeIntervalSince1970]*1000;
        pushQueue = dispatch_queue_create("push", NULL);
        //RTMP_SendChunk(<#RTMP *r#>, <#RTMPChunk *chunk#>)
    }
    
    return self;
}
- (void)sendSps:(NSData *)sps pps:(NSData *)pps
{
   dispatch_sync(pushQueue, ^{
       if(self->rtmp!= NULL)
       {
           RTMPPacket * packet;
           unsigned char * body;
           const char *spsPointer = sps.bytes;
           const char *ppsPointer = pps.bytes;
           int i;
           
           packet = (RTMPPacket *)malloc(128);
           NSLog(@"%ld",RTMP_HEAD_SIZE);
           memset(packet,0,RTMP_HEAD_SIZE);
           
           packet->m_body = (char *)packet + RTMP_HEAD_SIZE;
           body = (unsigned char *)packet->m_body;
           i = 0;
           body[i++] = 0x17;
           body[i++] = 0x00;
           
           body[i++] = 0x00;
           body[i++] = 0x00;
           body[i++] = 0x00;
           
           /*AVCDecoderConfigurationRecord*/
           body[i++] = 0x01;
           body[i++] = spsPointer[1];
           body[i++] = spsPointer[2];
           body[i++] = spsPointer[3];
           body[i++] = 0xff;
           
           /*sps*/
           body[i++]   = 0xe1;
           body[i++] = (sps.length >> 8) & 0xff;
           body[i++] = sps.length  & 0xff;
           memcpy(&body[i],spsPointer,sps.length );
           i +=  sps.length ;
           
           /*pps*/
           body[i++]   = 0x01;
           body[i++] = (pps.length >> 8) & 0xff;
           body[i++] = (pps.length) & 0xff;
           memcpy(&body[i],ppsPointer,pps.length);
           i +=  pps.length;
           
           packet->m_packetType = RTMP_PACKET_TYPE_VIDEO;
           packet->m_nBodySize = i;
           packet->m_nChannel = 0x04;
           packet->m_nTimeStamp = 0;
           packet->m_hasAbsTimestamp = 0;
           packet->m_headerType = RTMP_PACKET_SIZE_MEDIUM;
           packet->m_nInfoField2 = self->rtmp->m_stream_id;
           NSLog(@"body --- %s",body);
           if(RTMP_IsConnected(self->rtmp))
           {
               //调用发送接口
               int success = RTMP_SendPacket(self->rtmp,packet,TRUE);
               if(success != 1)
               {
                   NSLog(@"send_video_sps_pps fail");
               }
           }
           free(packet);
       }
       else
       {
           NSLog(@"send_video_sps_pps RTMP is not ready");
       }
   });
}

- (void)sendEncodeData:(NSData *)data isKeyFrame:(BOOL)isKeyFrame
{
    dispatch_sync(pushQueue, ^{
        if(self->rtmp != NULL)
        {
            RTMPPacket * packet;
            unsigned char * body;
            const char *buffer = data.bytes;
            uint32_t timeoffset = [[NSDate date] timeIntervalSince1970]*1000 - self->start_time;  /*start_time为开始直播时的时间戳*/
            packet = (RTMPPacket *)malloc(RTMP_HEAD_SIZE + data.length + 9);
            memset(packet,0,RTMP_HEAD_SIZE);
            
            packet->m_body = (char *)packet + RTMP_HEAD_SIZE;
            packet->m_nBodySize = (uint32_t)data.length + 9;
            
            /*send video packet*/
            body = (unsigned char *)packet->m_body;
            memset(body,0,data.length + 9);
            
            /*key frame*/
            body[0] = 0x27;
            if (isKeyFrame)//此为关键帧
            {
                body[0] = 0x17;
            }
            
            body[1] = 0x01;   /*nal unit*/
            body[2] = 0x00;
            body[3] = 0x00;
            body[4] = 0x00;
            
            body[5] = (data.length >> 24) & 0xff;
            body[6] = (data.length >> 16) & 0xff;
            body[7] = (data.length >>  8) & 0xff;
            body[8] = (data.length ) & 0xff;
            
            /*copy data*/
            memcpy(&body[9],buffer,data.length);
            
            packet->m_hasAbsTimestamp = 0;
            packet->m_packetType = RTMP_PACKET_TYPE_VIDEO;
            packet->m_nInfoField2 = self->rtmp->m_stream_id;
            packet->m_nChannel = 0x04;
            packet->m_headerType = RTMP_PACKET_SIZE_MEDIUM;
            packet->m_nTimeStamp = timeoffset;
            NSLog(@"body --- %s",body);
            if(RTMP_IsConnected(self->rtmp))
            {
                // 调用发送接口
                
                int success = RTMP_SendPacket(self->rtmp,packet,TRUE);
                if(success != 1)
                {
                    NSLog(@"send_rtmp_video fail");
                }
            }
            free(packet);
        }
        else
        {
            NSLog(@"send_rtmp_video RTMP is not ready");
        }

    });

}
@end
